package org.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 *
 * @author gus
 */
public class DeepCopy
{
    public static <T extends Serializable> T deepCopy( T object ) throws Exception
    {
        T newObject = null;
        ByteArrayOutputStream bos = null;
        ObjectInputStream is = null;
        try
        {
            bos = getOutStream(object);
            is = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
            newObject = (T) is.readObject();
        } catch (Exception exc)
        {
            throw exc;
        } finally
        {
            if ( bos != null )
            {
                bos.close();
            }
            if ( is != null )
            {
                is.close();
            }
        }
        return newObject;
    }

    private static ByteArrayOutputStream getOutStream( Object object ) throws Exception
    {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        ObjectOutputStream os = null;
        try
        {
            os = new ObjectOutputStream(bos);
            os.writeObject(object);
        } catch (Exception exc)
        {
            throw exc;
        } finally
        {
            os.close();
        }
        return bos;
    }
}
